package com.euc.springbootframework.auth.manager;

import com.euc.springbootframework.entity.User;
import com.euc.springbootframework.service.auth.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class MyAuthenticationManager implements AuthenticationProvider{

    @Resource(name = "UserDetailsService")
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        if (verifyUser(auth.getPrincipal().toString(), auth.getCredentials().toString())) {
            return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), Collections.emptyList());
        }
        throw new BadCredentialsException("Bad Credentials");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    public boolean verifyUser(String username, String password){
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) userDetailsService.loadUserByUsername(username);
        if(user==null)
            throw new BadCredentialsException("User not exist");
        if(!user.getPassword().equals(password))
            throw new BadCredentialsException("Wrong Password");
        return true;
    }
}
